//
//  PersonListViewController.m
//  Paparazzi
//
//  Created by Miguel Sánchez Valdés on 27/04/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "PersonListViewController.h"
//#import "PhotosListViewController.h"


@implementation PersonListViewController

@synthesize sharedContext;
@synthesize fetcherResultsController;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
		self.title = @"Contacts";
    }
	
	 UITabBarItem *item = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemContacts tag:0];
	 self.tabBarItem = item; 
	 [item release];
	
    return self;
}*/

-(id)initWithStyle :(UITableViewStyle)style{
	
	if (self = [super initWithStyle:style])
	{
		FlickrFetcher *flickrFetcher = [FlickrFetcher sharedInstance];
		sharedContext = [flickrFetcher managedObjectContext];	
		
		
		NSFetchRequest *request = [[NSFetchRequest alloc] init];
		NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:sharedContext];
		[request setEntity:entity];
		
		NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
		NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
		[request setSortDescriptors:sortDescriptors];
		[request setFetchBatchSize:(NSUInteger)20];
		[sortDescriptors release];
		[sortDescriptor release];
		
		
		fetcherResultsController = [[NSFetchedResultsController alloc]
									initWithFetchRequest:request
									managedObjectContext:sharedContext
									sectionNameKeyPath:nil
									//cacheName:@"tempPerson"];				
									cacheName:nil];

		
		[request release];
	}
	return self;
}



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    
	[super viewDidLoad];

	self.title = @"Contacts";
	
	UITabBarItem *item = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemContacts tag:0];
	self.tabBarItem = item; 
	[item release];

	NSError *error;
	[fetcherResultsController performFetch:&error];
	
}





#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
	
	/*NSInteger size = [[fetcherResultsController sections] count];
	if (size == 0) {
		size = 1;
	}
    return size;*/
	
	return [[fetcherResultsController sections] count];

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
	/*
	NSArray *sections = [fetcherResultsController sections];
	NSInteger count = 0;
	
	if ([sections count]) {
		id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:section];
		count = [sectionInfo numberOfObjects];
	}
    return count;*/
	
	id <NSFetchedResultsSectionInfo> sectionInfo = [[fetcherResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	

    static NSString *CellIdentifier = @"Cell";
	
    // Dequeue or create a new cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
	
    Person *person = (Person *)[fetcherResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = [person name];
	
	NSSet *photoSet = [person photos];
	Photo *image = [photoSet anyObject];
	cell.imageView.image = [UIImage imageNamed :[image path]];
	
	[image release];   
	return [cell autorelease];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	

	NSLog(@"%@", indexPath);
	//NSLog(@"%@", (Person *) [fetcherResultsController objectAtIndexPath:indexPath]);

	contactDetails = [[PhotosListViewController alloc] initWithStyle:UITableViewStylePlain];
	Person *person = (Person*) [fetcherResultsController objectAtIndexPath:indexPath];

	[contactDetails setPerson:person];
	[contactDetails setTitle:[NSString stringWithFormat:@"Fotos de %@", [person name]]];

	//NSLog(@"%@", person);
	[self.navigationController pushViewController:contactDetails animated:YES];

}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    self.fetcherResultsController = nil;
}


- (void)dealloc {
	[sharedContext release];
	[fetcherResultsController release];
	[contactDetails release];
    [super dealloc];
}


@end
